
const Service = require('egg').Service

class FlowsService extends Service {
  // create===============================================>
  async create(payload) {
    return this.ctx.model.Flows.create(payload)
  }

  // destroy===============================================>  
  async destroy(_id) {
    const { ctx } = this
    const flows = await ctx.service.flows.find(_id)
    if (!flows) {
      ctx.throw(404, 'flows not found')
    }
    return ctx.model.Flows.findByIdAndRemove(_id)
  }

  // 新增之前调用(默认值，不一定需要)
  async new(payload) {
    const { ctx } = this
    return new ctx.model.Flows()
  }

  // update===============================================>
  async update(_id, payload) {
    const { ctx } = this
    const flows = await ctx.service.flows.find(_id)
    if (!flows) {
      ctx.throw(404, 'flows not found')
    }
    return ctx.model.Flows.findByIdAndUpdate(_id, payload)
  }

  // show===============================================>
  async show(_id) {
    const flows = await this.ctx.service.flows.find(_id)
    if (!flows) {
      this.ctx.throw(404, 'flows not found')
    }
    return this.ctx.model.Flows.findById(_id)
  }

  // index===============================================>
  async index(payload, id = undefined) {
    const { ctx } = this
    let { currentPage, pageSize, search, start, end, device } = payload

    // 分页
    pageSize = Number(pageSize || 10)
    currentPage = Number(currentPage || 1)
    const skip = (currentPage - 1) * pageSize

    // console.log(payload)
    // 排序
    const sort = { timestamp: -1 }

    // 对象映射
    let populate = ['device']

    // 查询参数
    let querys = {}
    if (start && end) {
      console.log(start, end)
      querys['$and'] = [
        { timestamp: { $gte: start } },
        { timestamp: { $lte: end } },
      ]
    }

    const rid = ctx.state.user && ctx.state.user.data.role // GET ID
    const role = await ctx.model.Role.findById(rid)

    if (role && role.access !== 'admin') {
      let _id = ctx.state.user && ctx.state.user.data._id // GET ID

      const devices = await ctx.model.Devices.find({ user: _id })
      const deviceids = devices.map(e => e._id)
      querys.device = { $in: deviceids }
    } else {

      if (device) {
        const deviceids = device.split(',')
        if (deviceids.length > 1) {
          pageSize = deviceids.length * 100
        }
        querys.device = { $in: device.split(',') }
      }
    }


    if (id) {
      querys.user = id
    }
    // console.log(querys)

    // db.sponsoreds.find({$and:[{startDate:{$lte:new Date()}},{endDate:{$gte:new Date()}}]})

    const res = await this.ctx.model.Flows.find(querys).limit(pageSize).skip(skip).sort(sort).populate(populate).exec()
    const count = await this.ctx.model.Flows.countDocuments(querys).exec()

    // 整理数据源 -> Ant Design Pro
    const list = res.map((e, i) => {
      const jsonObject = Object.assign({}, e._doc)
      // jsonObject.index = i
      jsonObject.timestamp = e.timestamp.getTime()
      jsonObject.device = e.device.deviceid
      return jsonObject
    })

    return { count, list, pageSize, currentPage }
  }

  // echarts ===============================================>
  async echarts(payload) {
    let { start, end, device } = payload
    // 排序
    const sort = { timestamp: -1 }
    // 对象映射
    const populate = ['device']

    // hour = hour || 24
    // 查询参数
    if (device) {

      let querys = {}

      // const endTime = new Date(end)
      // const startTime = new Date(start)
      // startTime.setHours(startTime.getHours() - 24)
      // console.log(start, end)

      const deviceids = device.split(',')

      // querys.device = { $in: device.split(',') }

      // console.log(querys)
      const echarts = []

      for (const did of deviceids) {
        querys['$and'] = [
          { timestamp: { $gte: start } },
          { timestamp: { $lte: end } },
          { device: did }
        ]
        const res = await this.ctx.model.Flows.find(querys).sort(sort).populate(populate).exec()
        // const count = await this.ctx.model.Flows.countDocuments(querys).exec()
        // 整理数据源 -> Ant Design Pro
        const list = res.map((e, i) => {
          const jsonObject = Object.assign({}, e._doc)
          // jsonObject.index = i
          jsonObject.timestamp = e.timestamp.getTime()
          jsonObject.device = e.device.deviceid
          return jsonObject
        })

        echarts.push({ name: list.length ? list[0].device : '', list: list })
      }

      return { list: echarts }
    } else {
      return { list: [] }
    }
  }

  // removes===============================================>
  async removes(values) {
    if (values.length > 0) {
      return this.ctx.model.Flows.deleteMany({ _id: { $in: values } })
    } else {
      return this.ctx.model.Flows.deleteMany({})
    }
  }

  // Commons===============================================>
  async find(id) {
    return this.ctx.model.Flows.findById(id)
  }

  async getFlows(device, step = 0 , hour = 6) {
    const { ctx } = this
    let count = 0
    if (device) {

      const now = new Date()
      // 起始时间
      if (step) {
        now.setHours(now.getHours() - (step))
      }

      const end = parseInt(now.getTime() / 1000)
      // console.log(now)
      now.setHours(now.getHours() - (hour))
      // console.log(now)
      const start = parseInt(now.getTime() / 1000)

      const url = `https://dcache.iqiyi.com/api/flow?endtime=${end}&starttime=${start}&deviceid=${device.deviceid}`

      console.log(url, new Date(start * 1000), new Date(end * 1000))
      // https://dcache.iqiyi.com/api/flow?deviceid=F5E1D8B7F758A37C&endtime=1597587593&starttime=1597505193
      const list = await ctx.curl(url, {
        dataType: 'json',
        timeout: 3000,
        // 参数必须按照 `user:password` 格式设置
        auth: 'ppio-pi:Pplive123',
      })
      
      const options = { upsert: true, new: true, setDefaultsOnInsert: true }
      if (list.data && list.data.data) {
        for (const item of list.data.data) {

          const query = { device: device._id, timestamp: item.timestamp }
          item.device = device._id

          const res = await ctx.model.Flows.findOneAndUpdate(query, item, options).exec()
          // console.log(res)
          count++
        }
      }
      console.log('get flow count ', count)
    }
    return count
  }

}

module.exports = FlowsService
